package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;

import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

public class Rcs5GCodeAttrHandler extends AbstractAttrHandler<KiteInst, AttrData>  {

    @Autowired
    IQuerySceneInstService querySceneInstService;
    @Autowired
    OperateInstAttrService operateInstAttrService;

    @Value("${interface.call.mode:hsf}")
    private String mode;

    @Override
    public void before(KiteAttr attr, KiteInst inst, String value, AttrData data) {

        // 变更业务的场景初始化过程中不校验
        if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(data.getServiceOfferId())
            && !KeyConsts.IFTRUE_T.equals(
                querySceneInstService.getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))
            || KiteStringUtils.equals(attr.getOldValue(), value)) {
            return;
        }

        //模版还原时，不做校验
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        //fixme 可能导致频繁访问缓存,上线临时处理方案
        if ("sceneTempl".equals(data.getExtAttributes().get("entry")) || (KiteMapUtils.isNotEmpty(extParams) && extParams.containsKey("nodeCode"))) {
            return;
        }

        KiteAttr accessAttr = inst.getAttr("200004168");
        KiteAttr chatbotAttr = inst.getAttr("200004272");
        // 两个参数必填，其中一个没值都不做校验
        if (Objects.nonNull(accessAttr) && Objects.nonNull(chatbotAttr)) {
            String accessCode = accessAttr.getValue();
            String chatbot = chatbotAttr.getValue();
            String code = "";
            if (KiteStringUtils.equals("200004168", attr.getFieldName())) {
                if (KiteStringUtils.isEmpty(chatbotAttr.getValue())) {
                    return;
                } else {
                    // 0-都可用 1-accessCode不可用 2-chatbot不可用
                    code = checkRcs5GCode(value, chatbot);
                }
            } else if (KiteStringUtils.equals("200004272", attr.getFieldName())) {
                if (KiteStringUtils.isEmpty(accessAttr.getValue())) {
                    return;
                } else {
                    // 0-都可用 1-accessCode不可用 2-chatbot不可用
                    code = checkRcs5GCode(accessCode, value);
                }
            }
            // 200004168--接入码 200004272--CHATBOT名称
            if ("1".equals(code)) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("接入码不可用，请重新填写");
            } else if ("2".equals(code)) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("CHATBOT名称不可用，请重新填写");
            }
        }

    }

    @Override
    public void set(KiteAttr attr, KiteInst inst, String value, AttrData data) {
        // 如果模板还原进来的，设为空。因为接入码要校验唯一性。
        if ("sceneTempl".equals(data.getExtAttributes().get("entry"))) {
            value = "";
        }
        super.set(attr, inst, value, data);
    }

    @Override
    public void after(KiteAttr attr, KiteInst inst, AttrData data) {
    	super.after(attr, inst, data);
    	Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        //重提
//        if (Objects.nonNull(extParams) && extParams.containsKey("nodeCode")) {
//            attr.setIsEdit("F");
//        }
    }

    //接入码校验
    public String checkRcs5GCode(String accessCode,String chatbot) {
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("OP_CODE", "5Gmessage_Available");

        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> requestParamReq = new HashMap<>();
        requestParamReq.put("ACCESS_CODE", accessCode);
        requestParamReq.put("CHATBOT_NAME", chatbot);
        uniBssBody.put("AVAILABLE_REQ", requestParamReq);
        reqMap.put("UNI_BSS_BODY", uniBssBody);
        InfServiceHelper.adaptGray(reqMap, requestParamReq);

        String result;
        if (KiteStringUtils.isEqual(mode, "http")) {
            result = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, reqMap, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            result = infExchangeService.exchange(new JSONObject(reqMap));
        }
        Map<?, ?> resultMap = LocalTokenUtil.checkRespParamAndGetObject(result, "AVAILABLE_RSP", Map.class);

        return KiteMapUtils.getString(resultMap, "ERROR_CODE");

    }
}
